package com.whoisaa.wifitransfer.ui.activity;

import android.content.BroadcastReceiver;
import android.content.Context;
import android.content.Intent;
import android.content.IntentFilter;
import android.net.DhcpInfo;
import android.net.NetworkInfo;
import android.net.wifi.WifiManager;
import android.os.Bundle;
import android.os.Handler;
import android.os.Message;
import android.view.View;
import android.widget.ListView;

import com.whoisaa.wifitransfer.IClientConnectionListener;
import com.whoisaa.wifitransfer.R;
import com.whoisaa.wifitransfer.WifiClientThread;
import com.whoisaa.wifitransfer.WifiTools;
import com.whoisaa.wifitransfer.base.BaseActivity;
import com.whoisaa.wifitransfer.bean.FileInfo;
import com.whoisaa.wifitransfer.ui.adapter.ProgressListAdapter;

import java.net.Socket;
import java.util.ArrayList;
import java.util.List;

import butterknife.Bind;
import butterknife.ButterKnife;

/**
 * @Description 收文件
 * @Author AA
 * @DateTime 16/4/15 下午12:03
 */
public class ReceiverActivity extends BaseActivity {

    public static final String TAG = "ReceiverActivity";
    public static final int INIT_ADAPTER = 2019;
    public static final int REFRESH_PROGRESS = 2020;
    private static final String TYPE_WIFI = "WIFI";
    private static final String EXTRA_INFO_UNKNOW = "<unknown ssid>";

    @Bind(R.id.lv_receiver)
    ListView mListView;
    private ProgressListAdapter mAdapter;
    private List<FileInfo> mDatas = new ArrayList<>();

    private WifiTools mWifiTools;
    private WifiClientThread mClientThread;
    private WifiStateReceiver mWifiReceiver;

    private String mIpAddress;
    private boolean mIsConnected;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_receiver);
        ButterKnife.bind(this);
        init();
    }

    @Override
    protected void onDestroy() {
        super.onDestroy();
        ButterKnife.unbind(this);
    }

    private void init() {
        mWifiTools = new WifiTools(this);
        connectWifi();
    }

    //连接指定Wi-Fi
    public void connectWifi() {
        registerReceiver();
        mWifiTools.connectWifi(WifiTools.WIFI_NAME, WifiTools.WIFI_NONE_PWD);
    }

    /**
     * 注册Wi-Fi网络状态监听器
     */
    private void registerReceiver() {
        if (mWifiReceiver == null) {
            mWifiReceiver = new WifiStateReceiver();
        }
        IntentFilter intentFilter = new IntentFilter();
        intentFilter.addAction(WifiManager.WIFI_STATE_CHANGED_ACTION);
        intentFilter.addAction(WifiManager.NETWORK_STATE_CHANGED_ACTION);
        registerReceiver(mWifiReceiver, intentFilter);
    }

    /**
     * 反注册Wi-Fi网络状态监听器
     */
    private void unregisterReceiver() {
        unregisterReceiver(mWifiReceiver);
        mWifiReceiver = null;
    }

    /**
     * Wi-Fi连接状态广播接收器
     */
    private class WifiStateReceiver extends BroadcastReceiver {

        @Override
        public void onReceive(Context context, Intent intent) {
            NetworkInfo networkInfo = intent.getParcelableExtra(WifiManager.EXTRA_NETWORK_INFO);
            if (networkInfo != null
                    && networkInfo.isConnected()
                    && networkInfo.isConnectedOrConnecting()
                    && networkInfo.getTypeName().equals(TYPE_WIFI)
                    && !networkInfo.getExtraInfo().equals(EXTRA_INFO_UNKNOW)) {
                while (true) {
                    try {
                        Thread.currentThread();
                        Thread.sleep(100);
                        DhcpInfo dhcpInfo = mWifiTools.getDhcpInfo();
                        if (dhcpInfo.gateway != 0) {
                            //连接成功
                            unregisterReceiver();
                            mIpAddress = intToIp(dhcpInfo.gateway);
                            toast("成功连接到" + mIpAddress);
                            startClientThread();
                            break;
                        }
                    } catch (InterruptedException e) {
                        e.printStackTrace();
                    }
                }
            }
        }
    }

    /**
     * 开启接收端线程
     */
    private void startClientThread() {
        mWifiTools.acquireWifiLock();
        mClientThread = new WifiClientThread(this, mHandler, mIpAddress, new IClientConnectionListener() {
            @Override
            public void onSuccess(Socket socket) {
                mClientThread.receive();
                sendMessage(mHandler, 10, "等待接收...");
            }

            @Override
            public void onFailure(Exception e) {
                sendMessage(mHandler, 10, "开启接收端线程出错: " + e.getMessage());
            }
        });
        mClientThread.start();
    }


    private Handler mHandler = new Handler() {

        @Override
        public void handleMessage(Message msg) {
            super.handleMessage(msg);
            switch (msg.what) {
                case INIT_ADAPTER:
                    mDatas = (List<FileInfo>) msg.obj;
                    if(!isEmpty(mDatas)) {
                        toast("初始化成功");
                        mAdapter = new ProgressListAdapter(getAppContext(), mDatas);
                        mListView.setAdapter(mAdapter);
                    } else {
                        toast("初始化适配器失败");
                    }
                    break;

                //更新传输列表进度
                case REFRESH_PROGRESS:
                    int position = msg.arg1;
                    int progress = msg.arg2;
                    updateListItem(position, progress);
                    break;

                default:
                    toast((String) msg.obj);
                    break;
            }
        }
    };

    /**
     * 刷新列表中单个列表项视图
     * @param position
     * @param progress
     */
    private void updateListItem(int position, int progress) {
        if (position < 0 || position > mDatas.size() - 1) {
            return;
        }

        int visiblePosition = mListView.getFirstVisiblePosition();
        View view = mListView.getChildAt(position - visiblePosition + mListView.getHeaderViewsCount());
        FileInfo fileInfo = mDatas.get(position);
        fileInfo.setProgress(progress);
        mAdapter.updateItem(view, position, fileInfo);
    }

    /**
     * 获取字符串的IP地址
     *
     * @param ipInt
     * @return
     */
    private String intToIp(int ipInt) {
        StringBuilder sb = new StringBuilder();
        sb.append((ipInt & 0xff)).append('.')
                .append((ipInt >> 8) & 0xff).append('.')
                .append((ipInt >> 16) & 0xff).append('.')
                .append(((ipInt >> 24) & 0xff));
        return sb.toString();
    }

}
